package com.deyou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.deyou.Constants;
import com.deyou.R;
import com.deyou.adapter.SearchCityAdapter;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.CityBean;
import com.deyou.model.CityDataSupport;
import com.deyou.model.LzyResponse;
import com.deyou.model.RegionListBean;
import com.deyou.util.AndroidUtils;
import com.deyou.util.Logger;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.reflect.TypeToken;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import org.litepal.crud.DataSupport;
import org.litepal.crud.async.SaveExecutor;
import org.litepal.crud.callback.SaveCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class HouseSearchActivity extends BaseActivity implements AMapLocationListener {

    @BindView(R.id.tv_search_key)
    TextView tvSearchKey;
    @BindView(R.id.btn_cancel_search)
    TextView btnCancelSearch;
    @BindView(R.id.tv_tab_one)
    TextView tvTabOne;
    @BindView(R.id.tab_line_one)
    View tabLineOne;
    @BindView(R.id.tab_one_layout)
    RelativeLayout tabOneLayout;
    @BindView(R.id.tv_tab_two)
    TextView tvTabTwo;
    @BindView(R.id.tab_line_two)
    View tabLineTwo;
    @BindView(R.id.tab_two_layout)
    RelativeLayout tabTwoLayout;
    @BindView(R.id.tv_tab_three)
    TextView tvTabThree;
    @BindView(R.id.tab_line_three)
    View tabLineThree;
    @BindView(R.id.tab_three_layout)
    RelativeLayout tabThreeLayout;
    @BindView(R.id.btn_clear_history)
    TextView btnClearHistory;
    @BindView(R.id.search_history_title_layout)
    RelativeLayout searchHistoryTitleLayout;
    //    @BindView(R.id.search_history_gridview)
//    RecyclerView searchHistoryGridview;
    @BindView(R.id.tv_recommond_title)
    TextView tvRecommondTitle;
    //    @BindView(R.id.recommond_city_gridview)
//    RecyclerView recommondCityGridview;
    @BindView(R.id.tv_my_location)
    TextView tvMyLocation;
    @BindView(R.id.my_location_layout)
    RelativeLayout myLocationLayout;
    @BindView(R.id.search_history_flow)
    TagFlowLayout searchHistoryFlow;
    @BindView(R.id.recommond_city_flow)
    TagFlowLayout recommondCityFlow;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    private double amapLon;
    private double amapLat;

    private SearchCityAdapter mAdapter;
    private SearchCityAdapter mHistoryAdapter;
    private List<RegionListBean.City> cityList = new ArrayList<>();
    private List<RegionListBean.City> historyCityList = new ArrayList<>();
    private boolean isLocationed = false;
    private String regionCode = "";
    private boolean isNeedLonLat = false;
    private String myCurrentCity = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_search);
        ButterKnife.bind(this);
        getRegionList();
        initListener();
    }

    private void initView() {
//        List<CityDataSupport> searchHistoryList = DataSupport.findAll(CityDataSupport.class);
        List<CityDataSupport> searchHistoryList = DataSupport.where("userId=?", SPUtils.getStringByKey(HouseSearchActivity.this, Constants.UserId)).find(CityDataSupport.class);
        for (CityDataSupport data : searchHistoryList) {
            RegionListBean.City city = new RegionListBean.City();
            city.regionId = data.regionId;
            city.regionName = data.regionName;
            city.type = data.type;
            historyCityList.add(city);
        }
        if (null != historyCityList && historyCityList.size() > 0) {
            mHistoryAdapter = new SearchCityAdapter(this, historyCityList);
            searchHistoryFlow.setAdapter(mHistoryAdapter);
            searchHistoryFlow.setVisibility(View.VISIBLE);
        } else {
            searchHistoryFlow.setVisibility(View.GONE);
        }

        mAdapter = new SearchCityAdapter(this, cityList);
        recommondCityFlow.setAdapter(mAdapter);
    }

    private void initListener() {
        recommondCityFlow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                //view.setVisibility(View.GONE);
                regionCode = cityList.get(position).regionId;
                isNeedLonLat = false;
                dealJump();
                if (null != cityList.get(position) && !TextUtils.isEmpty(SPUtils.getStringByKey(HouseSearchActivity.this, Constants.UserId))) {
                    saveSearchHistory(position);
                }
                return true;
            }
        });


        recommondCityFlow.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set<Integer> selectPosSet) {
            }
        });

        searchHistoryFlow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                //view.setVisibility(View.GONE);
                regionCode = historyCityList.get(position).regionId;
                isNeedLonLat = false;
                if (historyCityList.get(position).type == 2){
                    dealJump();
                } else if (historyCityList.get(position).type == 1){
                    Bundle bundle = new Bundle();
                    bundle.putString("resourceCode", regionCode);
                    AndroidUtils.startNextActivity(HouseSearchActivity.this, HouseResourceDetailActivity.class, bundle, false);
                }
                return true;
            }
        });

    }

    @OnClick({R.id.tv_search_key, R.id.btn_cancel_search, R.id.tab_one_layout, R.id.tab_two_layout,
            R.id.tab_three_layout, R.id.btn_clear_history, R.id.my_location_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search_key:
                AndroidUtils.startNextActivityForResultNoTranAnim(HouseSearchActivity.this, HouseSearchListActivity.class, null, 0);
                break;
            case R.id.btn_cancel_search:
                finish();
                break;
            case R.id.tab_one_layout:
                dealStatusTitle(1);
                break;
            case R.id.tab_two_layout:
                dealStatusTitle(2);
                break;
            case R.id.tab_three_layout:
                dealStatusTitle(3);
                break;
            case R.id.btn_clear_history:
                DataSupport.deleteAll(CityDataSupport.class, "userId=?", SPUtils.getStringByKey(HouseSearchActivity.this, Constants.UserId));
                searchHistoryFlow.setVisibility(View.GONE);
                break;
            case R.id.my_location_layout:
                if (isLocationed) {
                    isNeedLonLat = true;
                    dealJump();
                } else {
                    showToast("请先获取您的定位信息再查看附近房源");
                }
                break;
        }
    }

    private void dealStatusTitle(int status) {
        tabLineOne.setVisibility(View.GONE);
        tvTabOne.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineTwo.setVisibility(View.GONE);
        tvTabTwo.setTextColor(getResources().getColor(R.color.color_272424));
        tabLineThree.setVisibility(View.GONE);
        tvTabThree.setTextColor(getResources().getColor(R.color.color_272424));
        switch (status) {
            case 1:
                tabLineOne.setVisibility(View.VISIBLE);
                tvTabOne.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
            case 2:
                tabLineTwo.setVisibility(View.VISIBLE);
                tvTabTwo.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
            case 3:
                tabLineThree.setVisibility(View.VISIBLE);
                tvTabThree.setTextColor(getResources().getColor(R.color.color_FF832D));
                break;
        }
    }

    private void initAMapLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(this);
        mLocationClient.setLocationListener(this);

        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);

        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    private void getRegionList() {
        Type type = new TypeToken<LzyResponse<RegionListBean>>() {
        }.getType();
        ServerApi.<LzyResponse<RegionListBean>>getData(type, Urls.getRegionList, "", "")//
                .subscribeOn(Schedulers.io())//
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        showLoading();
                    }
                })//
                .map(new Function<LzyResponse<RegionListBean>, RegionListBean>() {
                    @Override
                    public RegionListBean apply(@NonNull LzyResponse<RegionListBean> response) throws Exception {
                        return response.data;
                    }
                })//
                .observeOn(AndroidSchedulers.mainThread())  //
                .subscribe(new Observer<RegionListBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                    }

                    @Override
                    public void onNext(@NonNull RegionListBean regionBean) {
                        if (null != regionBean && regionBean.hotcityList != null && regionBean.hotcityList.size() > 0) {
                            cityList = regionBean.hotcityList;
                            handler.sendEmptyMessage(1);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();            //请求失败
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //可在其中解析amapLocation获取相应内容。
                amapLat = aMapLocation.getLatitude();
                amapLon = aMapLocation.getLongitude();
                tvMyLocation.setText(aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getStreet() + aMapLocation.getStreetNum());
                isLocationed = true;
                myCurrentCity = aMapLocation.getCity();
            } else {
                //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                Logger.e(Logger.LOGTAG + "AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
                isLocationed = false;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initAMapLocation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        isLocationed = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务
        isLocationed = false;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    initView();
                    break;
            }
        }
    };

    private void dealJump() {
        Bundle bundle = new Bundle();
        if (isNeedLonLat) {
            bundle.putString("lonAndLat", amapLon + "," + amapLat);
            bundle.putString("regionCode", "");
            bundle.putString("myCurrentCity", myCurrentCity);
        } else {
            bundle.putString("lonAndLat", "");
            bundle.putString("regionCode", regionCode);
            bundle.putString("myCurrentCity", "");
        }

        AndroidUtils.startNextActivity(HouseSearchActivity.this, HouseSearchResultListActivity.class, bundle, false);
    }

    private void saveSearchHistory(int position) {
        CityDataSupport city = new CityDataSupport();
        city.regionId = cityList.get(position).regionId;
        city.regionName = cityList.get(position).regionName;
        city.userId = SPUtils.getStringByKey(HouseSearchActivity.this, Constants.UserId);
        city.type = 2;
        List<CityDataSupport> cityData = DataSupport.where("regionId=? and userId=?", cityList.get(position).regionId, SPUtils.getStringByKey(HouseSearchActivity.this, Constants.UserId)).find(CityDataSupport.class);
        if (null == cityData || cityData.size() <= 0) {
            city.saveAsync().listen(new SaveCallback() {
                @Override
                public void onFinish(boolean success) {
                    Logger.i(Logger.LOGTAG + "保存记录", success + "");
                }
            });
        }
    }
}
